package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.*;
import com.qf.pojo.*;
import com.qf.service.DtsGoodsAttributeService;
import com.qf.service.DtsGoodsProductService;
import com.qf.service.DtsGoodsService;
import com.qf.service.DtsGoodsSpecificationService;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Override
    public Integer getTotal() {
        return goodsMapper.selectCount(null);
    }

    @Override
    public IPage<DtsGoods> queryPage(Integer page, Integer limit, String sort, String order, String goodsSn, String name, List<Integer> brandIds) {
        //分页参数
        IPage<DtsGoods> ipage = new Page<>(page,limit);

        //查询条件
        QueryWrapper<DtsGoods> qw = new QueryWrapper<>();
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            if(order.equalsIgnoreCase("desc")) {
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }
        }

        if(!StringUtils.isEmpty(goodsSn)) {
            qw.like("goods_sn", goodsSn);
        }

        if(!StringUtils.isEmpty(name)) {
            qw.like("name", name);
        }
        //brand_id in (1,2,3,4)
        if(!CollectionUtils.isEmpty(brandIds)) {
            qw.in("brand_id", brandIds);
        }

        goodsMapper.selectPage(ipage, qw);

        return ipage;
    }

    @Autowired
    DtsGoodsAttributeMapper attributeMapper;

    @Autowired
    DtsGoodsProductMapper productMapper;

    @Autowired
    DtsGoodsSpecificationMapper specificationMapper;

    @Autowired
    DtsCategoryMapper categoryMapper;

    @Override
    public Map<String, Object> queryDetailById(Integer id) {
        // 查询商品基本信息
        DtsGoods goods = goodsMapper.selectById(id);
        //商品的属性信息
        LambdaQueryWrapper<DtsGoodsAttribute> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(DtsGoodsAttribute::getGoodsId , id);
        qw1.eq(DtsGoodsAttribute::getDeleted, false); //只查询没有被逻辑删除的属性

        List<DtsGoodsAttribute> attributes = attributeMapper.selectList(qw1);

        //查询商品的库存
        LambdaQueryWrapper<DtsGoodsProduct> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(DtsGoodsProduct::getGoodsId , id);
        qw2.eq(DtsGoodsProduct::getDeleted, false); //只查询没有被逻辑删除的属性

        List<DtsGoodsProduct> products = productMapper.selectList(qw2);

        //查询商品的规格
        LambdaQueryWrapper<DtsGoodsSpecification> qw3 = new LambdaQueryWrapper<>();
        qw3.eq(DtsGoodsSpecification::getGoodsId , id);
        qw3.eq(DtsGoodsSpecification::getDeleted, false); //只查询没有被逻辑删除的属性

        List<DtsGoodsSpecification> specifications = specificationMapper.selectList(qw3);

        //查询商品的分类
        //获取商品的二级分类
        Integer categoryLv2 = goods.getCategoryId();
        //获取二级分类对应一级分类id
        DtsCategory category = categoryMapper.selectById(categoryLv2);
        //一级分类id
        Integer pid = category.getPid();

        Map<String,Object> data = new HashMap<>();
        //分类id
        data.put("categoryIds", Arrays.asList(pid, categoryLv2) );
        data.put("goods", goods);
        data.put("attributes", attributes);
        data.put("specifications", specifications);
        data.put("products", products) ;

        return data;
    }

    @Autowired
    DtsBrandMapper brandMapper;

    private Object checkParam(GoodsAllinone goodsAllinone) {
        //获取商品信息
        DtsGoods goods = goodsAllinone.getGoods();
        if(goods == null){
            return ResponseUtil.badArgument();
        }

        if(StringUtils.isEmpty(goods.getName())) {
            return AdminResponseUtil.fail(-1, "商品名称不能为空");
        }

        if(StringUtils.isEmpty(goods.getGoodsSn())) {
            return AdminResponseUtil.fail(-1, "商品编号不能为空");
        }
        //品牌id
        Integer brandId = goods.getBrandId();
        //判断id是否存在
        DtsBrand brand = brandMapper.selectById(brandId);
        if(brand == null) {
            return AdminResponseUtil.fail(-1, "品牌商不存在");
        }

        //获取分类id
        Integer categoryId = goods.getCategoryId();
        DtsCategory category = categoryMapper.selectById(categoryId);
        if(category == null) {
            return AdminResponseUtil.fail(-1, "分类不存在");
        }

        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes == null && attributes.length == 0) {
            return AdminResponseUtil.fail(-1, "商品属性不能为空");
        }

        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if(products == null && products.length == 0) {
            return AdminResponseUtil.fail(-1, "商品库存不能为空");
        }
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications == null && specifications.length == 0) {
            return AdminResponseUtil.fail(-1, "商品规格不能为空");
        }
        return null;
    }

    @Autowired
    DtsGoodsProductService productService;

    @Autowired
    DtsGoodsSpecificationService specificationService;

    @Autowired
    DtsGoodsAttributeService attributeService;

    @Override
    public Object update(GoodsAllinone goodsAllinone) {
        //数据校验
        Object result = this.checkParam(goodsAllinone);
        if(result != null) {
            return result;
        }

        //更新商品表
        DtsGoods goods = goodsAllinone.getGoods();
        goods.setUpdateTime(new Date());
        goodsMapper.updateById(goods);

        //更新库存表(多个)
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        productService.updateProducts(goods.getId(),products );

        //更新规格表
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        specificationService.updateSpecifications(goods.getId(),specifications);

        //更新属性表
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        attributeService.updateAttributes(goods.getId(), attributes);

        return ResponseUtil.ok();
    }

    /**
     * 0. 判断该商品是否被订单关联（未支付，支付失败。。。。）
     * 1. 对商品进行逻辑删除
     * 2. 对商品相关的 库存，规格，属性 进行逻辑删除
     * @param goods
     * @return
     */
    @Override
    public Object delete(DtsGoods goods) {
        long count = goodsMapper.selectOrderCountById(goods.getId());
        if(count > 0) {
            return ResponseUtil.fail(-1, "该商品正在热卖");
        }
        //把商品 逻辑删除
        goods.setDeleted(true);
        goodsMapper.updateById(goods);

        //把商品属性逻辑删除
        attributeService.deleteByGoodsId(goods.getId());
        //把商品规格逻辑删除
        specificationService.deleteByGoodsId(goods.getId());
        //把商品库存逻辑删除
        productService.deleteByGoodsId(goods.getId());

        return ResponseUtil.ok();
    }

    /**
     * 四张表添加数据
     * @param goodsAllinone
     * @return
     */
    @Override
    public Object create(GoodsAllinone goodsAllinone) {

        Object result = this.checkParam(goodsAllinone);

        if(result != null) {
            return result;
        }

        DtsGoods goods = goodsAllinone.getGoods();

        //再判断商品的名称是否重复
        LambdaQueryWrapper<DtsGoods> qw = new LambdaQueryWrapper<>();
        qw.eq(DtsGoods::getName, goods.getName());
        Integer count = goodsMapper.selectCount(qw);
        //如果count大于0，说明此商品名称已存在
        if(count > 0) {
            return ResponseUtil.fail(-1, "此商品已存在");
        }

        //添加商品
        goods.setDeleted(false);
        goods.setUpdateTime(new Date());
        goods.setAddTime(new Date());
        goodsMapper.insert(goods);
        //添加属性
        attributeService.addAttribute(goods.getId(), goodsAllinone.getAttributes());
        //添加规格
        productService.addProduct(goods.getId(), goodsAllinone.getProducts());
        //添加库存
        specificationService.addSpecification(goods.getId(), goodsAllinone.getSpecifications());

        return ResponseUtil.ok();
    }
}
